﻿Imports System.Data.SqlClient
Imports System.Data
Public Class AddVoteToSolution
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Question_ID = Request.Params("Questions_FK")
        If Request.Params("ID") = "" Or Request.Params("Questions_FK") = "" Then
            Response.Redirect("Default.aspx")
        End If
        If IsPostBack = False Then
            Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("BooksReviewDBConnectionString1").ConnectionString.ToString)
            Dim book_FK As Integer = 0
            'Find the id of the book to redirect back
            Dim findBookcmd As New SqlCommand("SELECT * FROM Questions WHERE ID = @f1", conn)
            conn.Open()
            findBookcmd.CommandType = CommandType.Text
            findBookcmd.Parameters.AddWithValue("@f1", Request.Params("Questions_FK"))
            'Find out if there any records at all (returned)
            Dim dr As SqlDataReader = findBookcmd.ExecuteReader()
            'this shows if any data is returned
            If dr.HasRows Then
                dr.Read()
                If Not IsDBNull(dr("Book_FK")) Then book_FK = dr("Book_FK")
            End If
            conn.Close()
            dr.Close()

            'check of the user has already voted
            Dim findVotercmd As New SqlCommand("SELECT * FROM Solution_Votes WHERE Voter = @f1 And Solution_FK = @f2", conn)
            conn.Open()
            findVotercmd.CommandType = CommandType.Text
            findVotercmd.Parameters.AddWithValue("@f1", User.Identity.Name)
            findVotercmd.Parameters.AddWithValue("@f2", Request.Params("ID"))
            'Find out if there any records at all (returned)
            Dim drVoter As SqlDataReader = findVotercmd.ExecuteReader()
            'this shows if any data is returned
            If drVoter.HasRows Then
                'dont
            Else
                drVoter.Close()
                Dim cmd As New SqlCommand("INSERT INTO [Solution_Votes] ([Solution_FK], [Voter]) VALUES (@f1, @f2)", conn)
                Dim SqlString As String = ""

                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@f1", Request.Params("ID"))
                cmd.Parameters.AddWithValue("@f2", User.Identity.Name)
                cmd.ExecuteNonQuery()
            End If
            drVoter.Close()
            conn.Close()
            If book_FK > 0 Then
                Response.Redirect(String.Format("ViewQuestion.aspx?Question={0}&Book_FK={1}", Question_ID, book_FK))
            End If
            Response.Redirect("Default.aspx")
        End If
    End Sub

End Class